let customerlistModel = (function () {
  let $selectBox = $(".selectBox"),
    $searchInp = $(".searchInp"),
    $tableBox = $(".tableBox"),
    $tbody = $tableBox.find('tbody'),
    $pageBox = $('.pageBox');

  // lx=my&type=''&search=''&limit=10&page=1
  // limit 每页请求条数 page总页数
  let lx = 'my',
    limit = 10,
    page = 1,
    total = 0,
    totalPage = 1;

  // 从服务器获取数据并渲染绑定到页面上
  async function bindHTML() {
    let result = await axios.get("/customer/list", {
      params: {
        lx,
        type: $selectBox.val(),
        search: $searchInp.val().trim(),
        limit, page,
      }
    })
    console.log(result)

    // 优化：请求数据先做一次清空
    $tbody.html('');
    $pageBox.html('')

    if (result.code != 0) {
      // 在数据为空的时候要清空之前已经绑定好的（优化：请求数据先做一次清空）
      // $tbody.html('');
      // $pageBox.html('')
      return;
    }
    // 存储总数及总页数
    total = parseInt(result.total);
    totlaPage = parseInt(result.totlaPage);

    // 生成列表DOM并渲染
    let str = '';
    result.data.forEach(item => {
      let {
        QQ,
        address,
        email,
        id,
        name,
        phone,
        sex,
        type,
        userId,
        userName,
        weixin,
      } = item;
      str += `
      <tr>
				<td class="w8">${name}</td>
				<td class="w5">${sex == 0 ? '男' : '女'}</td>
				<td class="w10">${email}</td>
				<td class="w10">${phone}</td>
				<td class="w10">${weixin}</td>
				<td class="w10">${QQ}</td>
				<td class="w5">${type}</td>
				<td class="w8">${userName}</td>
				<td class="w20">${address}</td>
				<td class="w14" customerlistId="${id}">
					<a href="javascript:;">编辑</a>
					<a href="javascript:;">删除</a>
					<a href="./visit.html?customerId=${id}">回访记录</a>
				</td>
			</tr>s
      `;
    })
    $tbody.html(str);

    // 分页计算处理
    total = parseInt(result.total);
    totalPage = parseInt(result.totalPage);

    // 如果总页数为1或者没有的情况下，分页就不需要展示（优化：请求数据先做一次清空）
    // $pageBox.html('');

    if (totalPage > 1) {
      str = '';
      page > 1 ? str += `<a href="javascript:;">上一页</a>` : null;
      str += `<ul class="pageNum">`;
      for (let i = 1; i <= totalPage; i++) {
        str += `<li class="${page == i ? 'active' : ''}">${i}</li>`;
      }
      str += `</ul>`;
      page < totalPage ? str += `<a href="javascript:;">下一页</a>` : null;
      $pageBox.html(str)
    }

  }
  // 处理下拉框和搜索重新获取获取数据筛选绑定
  function handle() {
    $selectBox.change(bindHTML);
    $searchInp.keydown(function (ev) {
      if (ev.keyCode === 13) {
        bindHTML();
      }
    })
    $pageBox.click(function (ev) {
      let target = ev.target,
        TAG = target.tagName,
        TEXT = target.innerText,
        temp = page;

      if (TAG === 'A') {
        if (TEXT === '上一页') {
          temp > 1 ? temp-- : 1;
        }
        if (TEXT === '下一页') {
          temp < totalPage ? temp++ : totalPage;
        }
      }
      if (TAG === 'LI') {
        temp = parseInt(TEXT);
      }
      // 优化项：如果点击的是当前此页面，就不做处理
      if (temp !== page) {
        page = temp;
        bindHTML();
      }
    })
    $tbody.click(async ev => {
      // ev.preventDefault();
      let target = ev.target,
        TAG = target.tagName,
        TEXT = target.innerText,
        customerId = $(target).parent().attr('customerlistid');
      if (TAG === 'A') {
        if (TEXT === '编辑') {
          window.location.href = `customeradd.html?customerId=${customerId}`;
          return;
        }
        if (TEXT === '删除') {
          let flag = confirm('Are you Sure');
          if (flag) {
            let result = await axios.get("/customer/delete", { params: { customerId } });
            if (result.code !== 0) {
              alert("删除失败，请重试");
              return;
            }
            bindHTML();
          }
        }
      }
    })
  }
  return {
    init() {
      // 获取传递进来的参数
      let params = window.location.href.queryURLParams();
      params.lx ? lx = params.lx : null;

      bindHTML();
      handle();

    }
  }
})();

customerlistModel.init();